/**
 * Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.stylefeng.guns.modular.api.controller;

import cn.stylefeng.guns.base.auth.service.AuthService;
import cn.stylefeng.guns.core.util.WxTool;
import cn.stylefeng.guns.modular.modules.entity.ModuleInfo;
import cn.stylefeng.guns.modular.modules.model.params.ModuleInfoParam;
import cn.stylefeng.guns.modular.modules.service.ModuleInfoService;
import cn.stylefeng.guns.modular.score.entity.ScoreInfo;
import cn.stylefeng.guns.modular.score.model.result.ScoreInfoResult;
import cn.stylefeng.guns.modular.score.service.ScoreInfoService;
import cn.stylefeng.guns.modular.teaminfo.entity.TeamInfo;
import cn.stylefeng.guns.modular.teaminfo.service.TeamInfoService;
import cn.stylefeng.guns.modular.userinfo.entity.UserInfo;
import cn.stylefeng.guns.modular.userinfo.service.UserInfoService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * rest方式的登录控制器
 *
 * @author fengshuonan
 * @Date 2017年1月10日 下午8:25:24
 */
@Controller
@RequestMapping("/wxapi")
@Api(tags = "系统登录")
public class ApiController extends BaseController {

    @Resource
    private AuthService authService;

    @Resource
    private UserService userService;

    @Resource
    private TeamInfoService teamInfoService;

    @Resource
    private ModuleInfoService moduleInfoService;

    @Resource
    private ScoreInfoService scoreInfoService;

    @Resource
    private UserInfoService userInfoService;
    
    
    /**
     * 点击登录执行的动作
     *
     * @author fengshuonan
     * @Date 2018/12/23 5:42 PM
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("登录接口")
    public Object restLogin(@RequestParam(value="user_name",required=false) String userName,
    							@RequestParam("phone") String phone,
                                  @RequestParam("activation_code") String activationCode,
                            @RequestParam(value="code",required=false) String code) {

        Map<String,Object> map = new HashMap<>();

//        if(ToolUtil.isEmpty(code)){
//            map.put("msg","code不能为空");
//            map.put("user_id","");
//            map.put("leader","");
//            map.put("team_id","");
//            map.put("code",500);
//            return map;
//        }

  //      Map<String,String> wxmap = WxTool.getLoginInfo(code);





//        if(ToolUtil.isEmpty(wxmap)){
//            map.put("msg","微信登录失败");
//            map.put("user_id","");
//            map.put("leader","");
//            map.put("team_id","");
//            map.put("code",500);
//            return map;
//        }
//
//        if(ToolUtil.isEmpty(wxmap.get("openid"))){
//            map.put("msg","openid获取失败");
//            map.put("user_id","");
//            map.put("leader","");
//            map.put("team_id","");
//            map.put("code",500);
//            return map;
//        }

        //判断是否为空
        if (ToolUtil.isOneEmpty( phone,activationCode)) {
            map.put("msg","手机号、激活码不能为空");
            map.put("user_id","");
            map.put("leader","");
            map.put("team_id","");
            map.put("code",500);
            return map;
        }
        //获取用户信息
        UserInfo ui = userInfoService.getOne(new QueryWrapper<UserInfo>()
                .eq("phone",phone));

        //查询小队
        TeamInfo ti = teamInfoService.getOne(new QueryWrapper<TeamInfo>()
                .eq("activation_code",activationCode));

        //判断队伍是否存在
        if(ToolUtil.isEmpty(ti)){
            map.put("msg","激活码不存在");
            map.put("user_id","");
            map.put("leader","");
            map.put("team_id","");
            map.put("code",500);
            return map;
        }

        if(ToolUtil.isOneEmpty(ti.getLeaderPhone(),ti.getMember1Phone(),ti.getMember2Phone(),ti.getMember3Phone(),ti.getMember4Phone())){
            map.put("msg","小队人员信息缺失，phone为空");
            map.put("user_id","");
            map.put("leader","");
            map.put("team_id","");
            map.put("code",500);
            return map;
        }


        //判断是否有此用户 没有的话去查小队表
        if(ToolUtil.isEmpty(ui)){

            UserInfo newui = new UserInfo();

            //比对成员 队长
            if(ti.getLeaderPhone().equals(phone)){
                newui.setPhone(phone);
                newui.setUserId(ti.getLeaderId());
                newui.setActivationCode(activationCode);
                if(ToolUtil.isNotEmpty(userName)){
                    newui.setUserName(userName);
                }
                map.put("openid",ti.getLeaderOpenid());
                map.put("userName",ti.getLeaderName());
            }else if(ti.getMember1Phone().equals(phone)){
                newui.setPhone(phone);
                newui.setUserId(ti.getMember1Id());
                newui.setActivationCode(activationCode);
                if(ToolUtil.isNotEmpty(userName)){
                    newui.setUserName(userName);
                }
                map.put("openid",ti.getMember2Openid());
                map.put("userName",ti.getMember1Name());
            }else if(ti.getMember2Phone().equals(phone)){
                newui.setPhone(phone);
                newui.setUserId(ti.getMember2Id());
                newui.setActivationCode(activationCode);
                if(ToolUtil.isNotEmpty(userName)){
                    newui.setUserName(userName);
                }
                map.put("openid",ti.getMember3Openid());
                map.put("userName",ti.getMember2Name());
            }else if(ti.getMember3Phone().equals(phone)){
                newui.setPhone(phone);
                newui.setUserId(ti.getMember3Id());
                newui.setActivationCode(activationCode);
                if(ToolUtil.isNotEmpty(userName)){
                    newui.setUserName(userName);
                }
                map.put("openid",ti.getMember4Openid());
                map.put("userName",ti.getMember3Name());
            }else if(ti.getMember4Phone().equals(phone)){
                newui.setPhone(phone);
                newui.setUserId(ti.getMember4Id());
                newui.setActivationCode(activationCode);
                if(ToolUtil.isNotEmpty(userName)){
                    newui.setUserName(userName);
                }
                map.put("openid",ti.getMember5Openid());
                map.put("userName",ti.getMember4Name());
            }else {
                map.put("msg","小队无此成员");
                map.put("user_id","");
                map.put("leader","");
                map.put("team_id","");
                map.put("code",500);
                return map;
            }

            userInfoService.save(newui);

            ui = newui;

//            UserInfo newui = new UserInfo();
//            newui.setUserName(username);
//            newui.setUsewechatId(usewechatId);
//
//            
//            List<Object> lo = new ArrayList<Object>();
//            Map<String,Object> leader = new HashMap<String, Object>();
//            leader.put("user_id", ti.getLeaderId());
//            leader.put("user_name", ti.getLeaderName());
//            leader.put("leader", 1);
//            lo.add(leader);
//            
//            Map<String,Object> member1Id = new HashMap<String, Object>();
//            member1Id.put("user_id", ti.getMember1Id());
//            member1Id.put("user_name", ti.getMember1Name());
//            member1Id.put("leader", 0);
//            lo.add(member1Id);
//            
//            Map<String,Object> member2Id = new HashMap<String, Object>();
//            member2Id.put("user_id", ti.getMember2Id());
//            member2Id.put("user_name", ti.getMember2Name());
//            member2Id.put("leader", 0);
//            lo.add(member2Id);
//            
//            Map<String,Object> member3Id = new HashMap<String, Object>();
//            member3Id.put("user_id", ti.getMember3Id());
//            member3Id.put("user_name", ti.getMember3Name());
//            member3Id.put("leader", 0);
//            lo.add(member3Id);
//            
//            Map<String,Object> member4Id = new HashMap<String, Object>();
//            member4Id.put("user_id", ti.getMember4Id());
//            member4Id.put("user_name", ti.getMember4Name());
//            member4Id.put("leader", 0);
//            lo.add(member4Id);
            
//            map.put("msg","用户不存在");
//            map.put("user_id","");
//            map.put("leader","");
//            map.put("team_id","");
//            map.put("code",500);
//            return map;
        } else {
            //f返回openid
            if(ti.getLeaderPhone().equals(phone)){
                map.put("openid",ti.getLeaderOpenid());
                map.put("userName",ti.getLeaderName());
            }else if(ti.getMember1Phone().equals(phone)){
                map.put("openid",ti.getMember2Openid());
                map.put("userName",ti.getMember1Name());
            }else if(ti.getMember2Phone().equals(phone)){
                map.put("openid",ti.getMember3Openid());
                map.put("userName",ti.getMember2Name());
            }else if(ti.getMember3Phone().equals(phone)){
                map.put("openid",ti.getMember4Openid());
                map.put("userName",ti.getMember3Name());
            }else if(ti.getMember4Phone().equals(phone)){
                map.put("openid",ti.getMember5Openid());
                map.put("userName",ti.getMember4Name());
            }else {
                map.put("msg","小队无此成员");
                map.put("user_id","");
                map.put("leader","");
                map.put("team_id","");
                map.put("code",500);
                return map;
            }
        }
        
//        if(ToolUtil.isEmpty(ui.getActivationCode())) {
//        	ui.setActivationCode(activationCode);
//        	if(ToolUtil.isEmpty(ui.getUserName())&&ToolUtil.isNotEmpty(userName)) {
//            	ui.setUserName(userName);
//            }
//        	userInfoService.updateById(ui);
//        }
        //判断队长
//        if(ToolUtil.isEmpty(ti.getLeaderPhone())) {
//            map.put("msg","队长手机号不存在，请先维护队长手机号");
//            map.put("user_id","");
//            map.put("leader","");
//            map.put("team_id","");
//            map.put("code",500);
//        }
        
        //填充队长ID 队员ID
        
//        if(phone.equals(ti.getLeaderPhone())) {
//
//        	//填充队长ID
//        	if(ToolUtil.isEmpty(ti.getLeaderId())) {
//        		ti.setLeaderId(ui.getUserId());
//        		teamInfoService.updateById(ti);
//        	}
//        }else {
//
//        	//填充队员ID
//        	if(ToolUtil.isEmpty(ti.getMember1Id())) {
//            	ti.setMember1Id(ui.getUserId());
//            	teamInfoService.updateById(ti);
//            }else if(ToolUtil.isEmpty(ti.getMember2Id())&&!ui.getUserId().equals(ti.getMember1Id())) {
//            	ti.setMember2Id(ui.getUserId());
//            	teamInfoService.updateById(ti);
//            }else if(ToolUtil.isEmpty(ti.getMember3Id())&&!ui.getUserId().equals(ti.getMember1Id())&&!ui.getUserId().equals(ti.getMember2Id())) {
//            	ti.setMember3Id(ui.getUserId());
//            	teamInfoService.updateById(ti);
//            }else if(ToolUtil.isEmpty(ti.getMember4Id())&&!ui.getUserId().equals(ti.getMember1Id())&&!ui.getUserId().equals(ti.getMember2Id())&&!ui.getUserId().equals(ti.getMember3Id())) {
//            	ti.setMember4Id(ui.getUserId());
//            	teamInfoService.updateById(ti);
//            }else {
//            	map.put("msg","小队成员已满");
//                map.put("user_id","");
//                map.put("leader","");
//                map.put("team_id","");
//                map.put("code",500);
//            }
//        }
        
        Integer leader = 0;
        Integer team_id = ti.getTeamId();
        
        if(ui.getUserId().equals(ti.getLeaderId())) {
        	leader = 1;
        }
        
        map.put("teamName",ti.getTeamName());
        map.put("msg","登陆成功");
        map.put("user_id",ui.getUserId());
        map.put("leader",leader);
        map.put("team_id",team_id);
        map.put("code",200);
        return map;
    }
    
    
    /**
     * 更新用户信息
     *
     * @author fengshuonan
     * @Date 2018/12/23 5:42 PM
     */
    @RequestMapping(value = "/updUser", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("更新用户信息")
    public Object restLogin(@RequestParam("user_name") String username,
                                  @RequestParam("usewechat_id") String usewechatId,
                                  @RequestParam("activation_code") String activationCode,
                                  @RequestParam("user_id") Long userId) {

        Map<String,Object> map = new HashMap<>();

        //判断是否为空
        if (ToolUtil.isOneEmpty(username, usewechatId,activationCode,userId)) {
            map.put("msg","用户名、微信惟一值、激活码、用户ID不能为空");
            map.put("user_id","");
            map.put("leader","");
            map.put("team_id","");
            map.put("code",500);
            return map;
        }
        //获取用户信息
        UserInfo ui = userInfoService.getOne(new QueryWrapper<UserInfo>()
                .eq("user_name",username)
                .eq("usewechat_id",usewechatId)
                .eq("activation_code",activationCode));
        

        //查询小队
        TeamInfo ti = teamInfoService.getOne(new QueryWrapper<TeamInfo>()
                .eq("activation_code",activationCode));

        //判断队伍是否存在
        if(ToolUtil.isEmpty(ti)){
            map.put("msg","激活码不存在");
            map.put("user_id","");
            map.put("leader","");
            map.put("team_id","");
            map.put("code",500);
            return map;
        }

        //判断是否有此用户 没有就新增
        if(ToolUtil.isEmpty(ui)){

            UserInfo newui = new UserInfo();
            newui.setUserName(username);
            newui.setUsewechatId(usewechatId);
            newui.setUserId(userId);
            newui.setActivationCode(activationCode);
            
            userInfoService.save(newui);
            
            Integer leader = 0;
            if(newui.getUserId().equals(ti.getLeaderId())) {
            	leader = 1;
            }
            
            map.put("msg","登陆成功");
            map.put("user_id",newui.getUserId());
            map.put("leader",leader);
            map.put("team_id",ti.getTeamId());
            map.put("code",200);
            return map;
        }

        
        map.put("msg","当前用户已存在，请重新选择");
        map.put("user_id","");
        map.put("leader","");
        map.put("team_id",ti.getTeamId());
        map.put("code",500);
        return map;

    }



    @RequestMapping(value = "/getmModules", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("获取模块信息")
    public Object getmModules(@RequestParam("user_id") Long userId,
                            @RequestParam("team_id") Integer teamId) {

        Map<String,Object> map = new HashMap<>();

        //判断是否为空
        if (ToolUtil.isOneEmpty(userId, teamId)) {
            map.put("msg","用户ID和小队ID不能为空");
            map.put("module_list","");
            map.put("code",500);
            return map;
        }
        
        UserInfo ui = userInfoService.getById(userId);

        List<Map<String,Object>> lmi = moduleInfoService.listMaps();
        
        //模块标识   解锁用
        String[] lock = {"0","0","0","0"};
        
        //查询记录 为空直接解锁第一个
        //TODO
        
        
        for(int i=0;i<lmi.size();i++) {
        	Integer mid = (Integer) lmi.get(i).get("module_id");
        	
        	//查询是否有没有完成题目 如果有 不解锁
        	
        	ModuleInfoParam m = new ModuleInfoParam();
        	m.setModuleId(mid);
        	m.setAc(ui.getActivationCode());
        	
        	List<Integer> li = moduleInfoService.getTasksIds(m);
        	if(li.size()==0) {//解锁下个模块
//        		if(i==0) {//第一个直接解锁
//        			lmi.get(0).put("module_status", 1);
//        		}else {
//        			lmi.get(mkflag).put("module_status", 1);
//        		}
        		lock[i] = "1";
        		//lmi.get(i).put("module_status", 1);
        	}else {
//        		if(i==0) {//第一个直接解锁
//        			lmi.get(0).put("module_status", 1);
//        		}else {
//        			lmi.get(mkflag).put("module_status", 0);
//        		}
        		lock[i] = "0";
        		//lmi.get(i).put("module_status", 0);
        	}
        	
        	
        	
        }
        
    	if(lock[0].equals("1")) {
    		lmi.get(1).put("module_status", 1);
    	}else {
    		lmi.get(1).put("module_status", 0);
    	}
    	if(lock[1].equals("1")) {
    		lmi.get(2).put("module_status", 1);
    	}else {
    		lmi.get(2).put("module_status", 0);
    	}
    	if(lock[2].equals("1")) {
    		lmi.get(3).put("module_status", 1);
    	}else {
    		lmi.get(3).put("module_status", 0);
    	}

        map.put("msg","获取成功");
        map.put("module_list",lmi);
        map.put("code",200);

        return map;
    }



    @RequestMapping(value = "/getPaihang", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("获取排行")
    public Object getPaihang(@RequestParam("team_id") Integer teamId) {
    	
    	TeamInfo ti = teamInfoService.getById(teamId);

        Map<String,Object> map = new HashMap<>();

        //判断是否为空
        if (ToolUtil.isOneEmpty(teamId)) {
            map.put("msg","小队ID不能为空");
            map.put("total",null);
            map.put("code",500);
            return map;
        }

        //List<ScoreInfo> lsi = scoreInfoService.list(new QueryWrapper<ScoreInfo>().select().last("ORDER BY total_points DESC"));

        List<Map<String, Object>> lsi = scoreInfoService.getPmList();

        if(ToolUtil.isEmpty(lsi)){
            map.put("msg","无法查询排行数据，小队id不存在");
            map.put("total",null);
            map.put("code",500);
            return map;
        }


        List<Map<String,Object>> lm = new ArrayList<>();

        for(int i=0;i<lsi.size();i++){

            //TeamInfo ti2 = teamInfoService.getById(lsi.get(i).getTeamId());
            Map<String,Object> map2 = new HashMap<>();


            //查询答了多少题
            //Integer taskNum = scoreInfoService.getTaskNum(lsi.get(i).getTeamId());

            map2.put("score",lsi.get(i).get("score"));
            map2.put("order",i+1);
            map2.put("taskNum",lsi.get(i).get("taskNum"));
            map2.put("team_name",lsi.get(i).get("team_name"));
            map2.put("ys",lsi.get(i).get("ys"));

            lm.add(map2);
        }


        map.put("msg","获取成功");
        map.put("total", lm);
//        map.put("score",si.getTotalPoints());
//        map.put("order",pm);
//        map.put("team_name",ti.getTeamName());
//        map.put("ys",si.getYs());
//        map.put("total",lsi);
        map.put("code",200);
        return map;
    }


}